package com.learn.boot.datasource.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learn.boot.datasource.config.DataSourceContextHolder;
import com.learn.boot.datasource.config.DynamicRoutingDataSource;
import com.learn.boot.datasource.domain.DataSourceProperties;
import com.learn.boot.datasource.mapper.DataSourceMapper;
import com.learn.boot.datasource.service.ChangeDataSourceService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import java.util.List;

@Slf4j
@Service
public class ChangeDataSourceServiceImpl extends ServiceImpl<DataSourceMapper, DataSourceProperties> implements ChangeDataSourceService {

    @Resource
    private DataSourceMapper dataSourceMapper;

    @Resource
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Override
    public boolean changeDS(String datasourceId) {
        // 切换到默认数据源
        DataSourceContextHolder.removeDataSource();

        // 获取所有配置
        List<DataSourceProperties> dataSourcePropertiesList = dataSourceMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(dataSourcePropertiesList)) {
            for (DataSourceProperties dataSource : dataSourcePropertiesList) {
                if (dataSource.getDataSourceId().equals(datasourceId)) {
                    log.info("已经找到数据源,dataSourceId是：" + dataSource.getDataSourceId());
                    dynamicRoutingDataSource.checkCreateDataSource(dataSource);
                    // 切换数据源
                    DataSourceContextHolder.setDataSource(dataSource.getDataSourceId());
                    return Boolean.TRUE;
                }
            }
        }
        return Boolean.FALSE;
    }
}
